package frame.Good;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.GoodMapper;
import org.example.pojo.Good;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class GoodPanel extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private JLabel lblGoodCount; // 声明商品数量标签
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private GoodMapper goodMapper = sqlSession.getMapper(GoodMapper.class);

    public GoodPanel() {
        super("商品管理界面", true, true, true, true);
        this.setLayout(new BorderLayout());

        // 设置JInternalFrame的大小
        this.setSize(800, 600);

        // 最大化窗口
        try {
            this.setMaximum(true);
        } catch (Exception ex) {
            System.out.println("Internal frame maximization failed: " + ex.getMessage());
        }

        // 初始化 JTable
        table = new JTable() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置单元格不可编辑
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // 设置多选模式

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel(new BorderLayout()); // 使用BorderLayout布局
        this.add(buttonPanel, BorderLayout.SOUTH);

        // 添加商品数量文本标签
        lblGoodCount = new JLabel("商品数量: " + tableModel.getRowCount());
        lblGoodCount.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        buttonPanel.add(lblGoodCount, BorderLayout.WEST); // 放在按钮面板的最左侧

        // 创建一个面板用于放置按钮，使用FlowLayout，并设置居中对齐
        JPanel buttonCenterPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(buttonCenterPanel, BorderLayout.CENTER);

        // 添加按钮到中间面板
        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new goodadd());
            }
        });
        buttonCenterPanel.add(addButton);

        // 修改按钮
        JButton editButton = new JButton("修改");
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(GoodPanel.this, "直接在表格中编辑你想要修改的内容，然后点击确定修改", "提示", JOptionPane.WARNING_MESSAGE);
                GuanliPanel.setContent(new goodupdate());
            }
        });
        buttonCenterPanel.add(editButton);

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selectedRows = table.getSelectedRows();
                if (selectedRows.length == 0) {
                    JOptionPane.showMessageDialog(GoodPanel.this, "请选择要删除的商品！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String[] Gids = new String[selectedRows.length];
                for (int i = 0; i < selectedRows.length; i++) {
                    Gids[i] = (String) tableModel.getValueAt(selectedRows[i], 0);
                }

                int res = JOptionPane.showConfirmDialog(GoodPanel.this, "删除商品的同时也会删除商品相关的采购信息，是否确认要删除当前选中的商品？删除后数据无法找回，自己承担后果", "确认", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.YES_OPTION) {
                    goodMapper.deleteGood(Gids);
                    sqlSession.commit();
                }

                refreshTableData();
            }
        });
        buttonCenterPanel.add(deleteButton);

        // 查询按钮
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new goodselect());
            }
        });
        buttonCenterPanel.add(queryButton);

        // 导出CSV按钮
        JButton exportButton = new JButton("导出CSV文件");
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    exportToCSV();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        buttonPanel.add(exportButton, BorderLayout.EAST);

    }

    private void initializeTableData() {
        Object[] columnNames = {"商品编号", "商品名称", "商品价格", "客户编号", "商品介绍", "备注"};
        List<Good> goods = goodMapper.selectAll();

        Object[][] data = new Object[goods.size()][columnNames.length];
        for (int i = 0; i < goods.size(); i++) {
            Good good = goods.get(i);
            data[i][0] = good.getGid();
            data[i][1] = good.getGName();
            data[i][2] = good.getGPay();
            data[i][3] = good.getCid();
            data[i][4] = good.getGIntroduction();
            data[i][5] = good.getOther();
        }

        tableModel = new DefaultTableModel(data, columnNames);
        table.setModel(tableModel);

        updateGoodCountLabel(); // 更新商品数量显示
    }

    private void refreshTableData() {
        List<Good> goods = goodMapper.selectAll();

        tableModel.setRowCount(0);

        for (Good good : goods) {
            tableModel.addRow(new Object[]{
                    good.getGid(),
                    good.getGName(),
                    good.getGPay(),
                    good.getCid(),
                    good.getGIntroduction(),
                    good.getOther()
            });
        }

        updateGoodCountLabel(); // 更新商品数量显示
    }

    private void updateGoodCountLabel() {
        if (lblGoodCount != null) { // Add null check to prevent NullPointerException
            lblGoodCount.setText("商品数量: " + tableModel.getRowCount());
        }
    }

    private void exportToCSV() throws IOException {
        // 提示用户输入文件名
        String suggestedFileName = JOptionPane.showInputDialog(this, "请输入要导出的文件名（不包含扩展名.csv）:");

        if (suggestedFileName == null || suggestedFileName.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "文件名不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 设置导出文件的目录为绝对路径（例如：C:/Users/冉前辉/Desktop）
        File defaultDir = new File("C:/Users/冉前辉/Desktop");

        // 构造完整的文件名，确保以用户输入的文件名开头，添加 .csv 扩展名
        String fileName = suggestedFileName.trim() + ".csv";
        File fileToSave = new File(defaultDir, fileName);

        try (FileWriter fw = new FileWriter(fileToSave)) {
            // 写入表头
            for (int i = 0; i < tableModel.getColumnCount(); i++) {
                fw.append(tableModel.getColumnName(i));
                if (i < tableModel.getColumnCount() - 1) {
                    fw.append(",");
                } else {
                    fw.append("\n");
                }
            }

            // 写入数据
            for (int row = 0; row < tableModel.getRowCount(); row++) {
                for (int col = 0; col < tableModel.getColumnCount(); col++) {
                    fw.append(String.valueOf(tableModel.getValueAt(row, col)));
                    if (col < tableModel.getColumnCount() - 1) {
                        fw.append(",");
                    } else {
                        fw.append("\n");
                    }
                }
            }

            JOptionPane.showMessageDialog(this, "CSV文件已成功导出至:\n" + fileToSave.getAbsolutePath(), "导出成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "导出CSV文件时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }


}
